import { Divider, Pagination, Table, Tooltip } from "@arco-design/web-react";
import "./index.scss";
import React, {
  forwardRef,
  useEffect,
  useImperativeHandle,
  useRef,
  useState,
} from "react";
import { PageLinks } from "@/core/models/basic.model";
import DragContext from "./componets/DragContext";
import { useLocation } from "react-router-dom";
import { localStorage } from "@/utils/storage";
import * as _ from "lodash";
import IconFont from "../IconFont";
import CustomModal from "../CustomModal";
import CustomForm from "../CustomForm";
import useForm from "@arco-design/web-react/es/Form/useForm";
import {
  CTableColumnProps,
  CustomTablePropsInt,
  TableStyleInt,
} from "./utils/types";
import { defaultStyle, setDefaultProps, setFormItems } from "./utils/hooks";
import { fullScreen } from "@/utils";
import { useAppSelector } from "@/store/hooks";

const CustomTable = forwardRef((props: CustomTablePropsInt<any>, ref) => {
  const requestLoading = useAppSelector((state) => state.app.requestLoading);

  const location = useLocation();
  const id = props.id || location.pathname;
  const cache = localStorage.get(id);

  const [data, setData] = useState<any[]>([]);
  const [total, setTotal] = useState(0);
  const [pageParams, setPageParams] = useState<PageLinks>({
    page: 1,
    size: 20,
  });

  const [selectedRowKeys, setSelectedRowKeys] = useState<any[]>([]);
  const [selectedRows, setSelectedRows] = useState<any[]>([]);

  const onSelectChange = (selectedRowKeys: any[], selectedRows: any[]) => {
    setSelectedRowKeys(selectedRowKeys);
    setSelectedRows(selectedRows);
  };

  const [tableColumns, setTableColumns] = useState<CTableColumnProps[]>(
    setDefaultProps(props.columns)
  );
  const [tableStyle, setTableStyle] = useState<TableStyleInt>();

  const getData = async (params?: any) => {
    const req = { ...pageParams, ...params };
    console.log("表格请求参数-->", req);
    if (props.getData) {
      props.getData?.({ ...req }).then((res) => {
        setData(res.data.list);
        setTotal(res.data.total);
      });
    } else {
      setData(props.data || []);
      setTotal(props.data?.length || 0);
    }
  };

  useImperativeHandle(ref, () => ({
    getData,
  }));

  const onChange = (pageNumber: number, pageSize: number) => {
    setPageParams({ page: pageNumber, size: pageSize });
  };

  const getItems = (items: CTableColumnProps[]) => {
    setTableColumns(items);
  };

  /**
   * 根据缓存中的数据更新列
   * @param source
   * @returns
   */
  const handleColumn = (source: CTableColumnProps[]): CTableColumnProps[] => {
    const _columns = _.cloneDeep(source) as CTableColumnProps[];
    if (cache) {
      _columns.map((el) => {
        el.sort = cache.sort[el.dataIndex!];
        el.fixed = cache.fixed[el.dataIndex!];
      });
      _columns.sort((a, b) => a.sort - b.sort);
      return setDefaultProps(_columns);
    } else {
      return _columns;
    }
  };

  const getPopup = () => {
    return (
      <DragContext
        showKeys={showKeys}
        data={handleColumn(props.columns)}
        getItems={getItems}
      />
    );
  };

  //读取本地缓存的信息
  const [showKeys, setShowKeys] = useState<string[]>([]);
  const getCache = () => {
    const show = tableColumns.map((el) => el.dataIndex) as string[];
    const sort: Record<string, number> = {};
    const fixed: Record<string, string | undefined> = {};
    const cache = localStorage.get(id) || {};
    const localStyle = localStorage.get(id)?.style;
    const style: TableStyleInt = {
      ...defaultStyle,
      ...localStyle,
    };
    tableColumns.map((el, index) => {
      sort[el.dataIndex!] = index;
      fixed[el.dataIndex!] = el.fixed;
    });
    localStorage.set(id, {
      ...cache,
      show,
      sort,
      fixed,
      style,
    });
    setShowKeys(show);
    setTableStyle(localStyle ? localStyle : style);
  };

  const onRefresh = () => {
    getData();
  };

  useEffect(() => {
    getData();
  }, [pageParams]);

  useEffect(() => {
    getCache();
  }, [tableColumns]);

  useEffect(() => {
    props.selectChange?.(selectedRowKeys, selectedRows);
  }, [selectedRowKeys]);

  const [visible, setVisible] = useState(false);

  const [form] = useForm();

  const submitSetting = () => {
    const newStyle = form.getFieldsValue() as TableStyleInt;
    setTableStyle({ ...newStyle });
    updateStyle({ ...newStyle });
    setVisible(false);
  };

  const updateStyle = (newStyle: TableStyleInt) => {
    const cache = localStorage.get(id);
    localStorage.set(id, { ...cache, style: newStyle });
  };

  const [isFullscreen, setIsFullscreen] = useState(false);

  const handleFullScreen = () => {
    setIsFullscreen(!isFullscreen);
    fullScreen();
  };

  return (
    <div
      className={`flex-1 flex flex-col custom-table overflow-hidden pt-2 ${isFullscreen ? "fullscreen" : ""}`}
    >
      <div className="flex justify-between mb-2">
        <div>{props.operationButtons}</div>
        <div className="toolbox mr-4">
          <Tooltip color="#fff" content="刷新">
            <span
              className="hover:text-primary cursor-pointer"
              onClick={onRefresh}
            >
              <IconFont type="icon-shuaxin"></IconFont>
            </span>
          </Tooltip>

          <Divider type="vertical" />

          <Tooltip color="#fff" content="全屏">
            <span
              className="hover:text-primary cursor-pointer"
              onClick={handleFullScreen}
            >
              <IconFont type="icon-quanping"></IconFont>
            </span>
          </Tooltip>

          <Divider type="vertical" />

          <Tooltip color="#fff" content="设置">
            <span
              className="hover:text-primary cursor-pointer"
              onClick={() => setVisible(true)}
            >
              <IconFont type="icon-shezhi"></IconFont>
            </span>
          </Tooltip>

          <Divider type="vertical" />

          <Tooltip
            triggerProps={{
              popup: getPopup,
              trigger: "click",
              position: "bottom",
            }}
            color="#fff"
            content="设置"
          >
            <span className="hover:text-primary cursor-pointer">
              <IconFont type="icon-liebiao1"></IconFont>
            </span>
          </Tooltip>

          <Divider type="vertical" />

          <Tooltip color="#fff" content="宽度设置">
            <span
              className="hover:text-primary cursor-pointer"
              onClick={onRefresh}
            >
              <IconFont type="icon-kuanduzishiying"></IconFont>
            </span>
          </Tooltip>
        </div>
      </div>
      <div
        className="flex-1 overflow-hidden flex"
        style={{
          maxHeight: props.height || "none",
        }}
      >
        <Table
          loading={requestLoading}
          columns={tableColumns}
          data={data}
          borderCell
          rowKey={props.rowKey ?? "id"}
          pagination={false}
          {...tableStyle}
          rowSelection={{
            type: props.selectionType,
            selectedRowKeys,
            onChange: onSelectChange,
          }}
        />
      </div>
      <div className="bg-white p-2 mt-2">
        <Pagination
          showTotal
          total={total}
          showJumper
          sizeCanChange
          style={{ width: 800 }}
          pageSize={pageParams.size}
          current={pageParams.page}
          onChange={onChange}
        />
      </div>

      <CustomModal
        onCancel={() => setVisible(false)}
        onOK={submitSetting}
        title="表格设置"
        visible={visible}
      >
        <CustomForm
          wrap
          formAttrs={{
            layout: "inline",
            initialValues: { ...tableStyle },
          }}
          form={form}
          items={setFormItems}
          showBtn={false}
        ></CustomForm>
      </CustomModal>
    </div>
  );
});

export default CustomTable;
